package com.tonghe.servlet.user;

import com.alibaba.fastjson.JSONArray;
import com.mysql.cj.util.StringUtils;
import com.tonghe.pojo.Role;
import com.tonghe.pojo.User;
import com.tonghe.service.role.RoleService;
import com.tonghe.service.role.RoleServiceImpl;
import com.tonghe.service.user.UserService;
import com.tonghe.service.user.UserServiceImpl;
import com.tonghe.util.Constants;
import com.tonghe.util.PageSupport;
import org.junit.Test;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Date:2021/12/5- 12- 05- 21:29
 **/
public class UserServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String method = req.getParameter("method");
        if(method.equals("savepwd")&&method!=null){
            this.updatePwd(req, resp);
        }else if(method.equals("pwdmodify")&&method!=null){
            this.pwdModify(req, resp);
        }else if(method.equals("query")&&method!=null){
            this.query(req,resp);
        }
    }


    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
    public void updatePwd(HttpServletRequest req, HttpServletResponse resp){
        Object o = req.getSession().getAttribute(Constants.USER_SESSION);
        String newpassword = req.getParameter("newpassword");

//        System.out.println("servlet"+newpassword);

        boolean flag= false;

        System.out.println(o != null);
        System.out.println(StringUtils.isNullOrEmpty(newpassword));


        if( o != null && !StringUtils.isNullOrEmpty(newpassword)){
            UserService userService = new UserServiceImpl();
            flag = userService.updatePwd(((User)o).getId(),newpassword);
            if(flag ){
                req.setAttribute("message","密码修改成功，请推出使用新密码登陆");
                req.getSession().removeAttribute(Constants.USER_SESSION);
            }else {
                req.setAttribute("message","密码修改失败");
            }
        }else{
            req.setAttribute("message","新密码有问题");
        }
        try {
            req.getRequestDispatcher("pwdmodify.jsp").forward(req,resp);
        } catch (ServletException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void pwdModify(HttpServletRequest req, HttpServletResponse resp){
        //从Session中拿ID；
        Object o = req.getSession().getAttribute(Constants.USER_SESSION);
        String oldpassword = req.getParameter("oldpassword");

        //MAP 结果集
        Map<String,String> resultMap = new HashMap<String,String >();               //见pwdmodify.js
        if(o == null){
            resultMap.put("result","sessionerror");//Session过期
        }else if(StringUtils.isNullOrEmpty(oldpassword)){
            resultMap.put("result","error");//密码为空
        }else{
            String userPassword = ((User)o).getUserPassword();
            if(userPassword.equals(oldpassword)){
                resultMap.put("result","true");//密码正确
            }else{
                resultMap.put("result","false");//密码错误
            }
        }

        try{
            resp.setContentType("application/json");
            PrintWriter writer = resp.getWriter();

            writer.write(JSONArray.toJSONString(resultMap));
            writer.flush();
            writer.close();
        }catch (IOException e) {
            e.printStackTrace();
        }
    }
    //重难点
    private void query(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        /*
         * 从前端点击按钮到servlet servlet需要什么：我全都要
         * 并且，点击后是head.jsp && userlist.jsp 一起走的user.do method = query方法
         * */
        //查询用户列表
        // 从前端获取数据 从userlist.jsp中form表单来
        String queryUserName = req.getParameter("queryname");
        String temp = req.getParameter("queryUserRole");
        String pageIndex = req.getParameter("pageIndex");

        int queryUserRole = 0;//设为默认 0

        //获取用户列表
        UserService userService = new UserServiceImpl();
        List<User> userList = null;

        //第一次走这个请求，一定是第一页，然后页面大小是固定的
        int pageSize = Constants.pageSize;//默认是5  此处写死。后期可修改到配置文件之中
        int currentPageNo = 1;//设置当前页面默认为1 下面有修改


        if(queryUserName == null){
            queryUserName = "";
        }
        if(temp != null && !temp.equals("")){
            queryUserRole = Integer.parseInt(temp);//给查询赋值 0，1，2，3
        }
        if(pageIndex != null){
            currentPageNo = Integer.parseInt(pageIndex);
//            currentPageNo = Integer.valueOf(pageIndex);
        }
        //获取用户总数
        int totalCount = userService.getUserCount(queryUserName,queryUserRole);
        //总页数支持
        PageSupport pageSupport =new PageSupport();//工具类
        pageSupport.setCurrentPageNo(currentPageNo);
        pageSupport.setPageSize(Constants.pageSize);
        pageSupport.setTotalCount(totalCount);
//        System.out.println("totalCount = "+totalCount);

        int totalPageCount = ((int)(totalCount/pageSize))+1;
        System.out.println("totalPageCount = "+totalPageCount);

        //控制首页和尾页
        if(currentPageNo < 1){
            currentPageNo = 1;
        }else if(currentPageNo > totalPageCount){
            currentPageNo = totalPageCount;
        }

        //好戏开始了！！！！！！！！！！！！！！！！！！！！！！！！！！！！！！！！！！！！！！！！！！！！！！！！!
        //获取用户列表展示
        userList = userService.getUserList(queryUserName,queryUserRole,currentPageNo,pageSize);
//        System.out.println("userServlet"+currentPageNo+"\t"+pageSize);
        req.setAttribute("userList",userList);

        RoleService roleService = new RoleServiceImpl();
        List<Role> roleList = roleService.getRoleList();

        req.setAttribute("roleList",roleList);
        req.setAttribute("totalCount",totalCount);
        req.setAttribute("currentPageNo",currentPageNo);
        req.setAttribute("totalPageCount",totalPageCount);
        req.setAttribute("queryUserName",queryUserName);
        req.setAttribute("queryUserRole",queryUserRole);

        //返回前端
        try {
            req.getRequestDispatcher("userlist.jsp").forward(req,resp);
        } catch (ServletException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
    //添加用户
    public void add(HttpServletRequest req, HttpServletResponse resp) throws IOException{
        //前端数据读回
        String userCode = req.getParameter("userCode");
        String userName = req.getParameter("userName");
        String userPassword = req.getParameter("userPassword");
        String gender = req.getParameter("gender");
        String birthday = req.getParameter("birthday");
        String phone = req.getParameter("phone");
        String address = req.getParameter("address");
        String userRole = req.getParameter("userRole");

        User user = new User();
        user.setUserCode(userCode);
        user.setUserName(userName);
        user.setUserPassword(userPassword);
        user.setAddress(address);
        try {
            user.setBirthday(new SimpleDateFormat("yyyy-MM-dd").parse(birthday));
        } catch (ParseException e) {
            e.printStackTrace();
        }
        user.setGender(Integer.valueOf(gender));
        user.setPhone(phone);
        user.setUserRole(Integer.valueOf(userRole));
        user.setCreationDate(new Date());
        user.setCreatedBy(((User)req.getSession().getAttribute(Constants.USER_SESSION)).getId());//有一点点长

        UserService userService = new UserServiceImpl();
        if(userService.add(user)){//返回值是boolean哦
            resp.sendRedirect(req.getContextPath()+"/jsp/user.do?method=query");//重定向到查询
        }else{
            try {
                req.getRequestDispatcher("useradd.jsp").forward(req, resp);
            } catch (ServletException e) {
                e.printStackTrace();
            }
        }
    }


}
